<?php
$serv = new swoole_server("127.0.0.1", 9501,SWOOLE_PROCESS,SWOOLE_SOCK_TCP);

//链接redis
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
 
//设置异步任务的工作进程数量
$serv->set(array('task_worker_num' =>4));
 
//监听数据接收事件
$serv->on('receive', function($serv, $fd, $from_id, $data)  use ($redis) {

    echo '接受数据';

	global $redis;
	if(! empty($data))
	{
		$data 	=	unserialize($data);
		$loop 	=	true;
		$test 	=	$data['test'];			//测试专用
        $game_message 		=	'push_'.$data['game'];
        $update_message     =   'update_'.$data['game'];

		while ($loop) 
		{
            $value = $redis->lpop($game_message);

			if(! empty($value))
			{
				//投递异步任务
				$value          =   json_decode($value,true);
				$value['test']	=	$test;
				$value['game']	=	$data['game'];

                $result = $redis->rPush($update_message,$value['id']);

                if($result)
                {
                    echo '加入队列'.$update_message.' id='.$value['id'];
                }

				$task_id = $serv->task($value);//非阻塞
				
			}
			else
			{
				$loop	=	false;
			}
		}
		
		//发完了出发更新请求（删除）
		if(empty($loop))
		{
			//发起更新请求 call_back
			if(! empty($test))
			{
			    echo '发起测试回调';
				test_handleFun($data);		//测试专用
			}
			else
			{
                echo '发起正式回调';
				handleFun($data);			//正式专用
			}
		}
		
	}
    
});
 
 
//处理异步任务
$serv->on('task', function ($serv, $task_id, $from_id, $data){
	
	echo "接收异步任务[id=$task_id]".PHP_EOL;
	
	//执行推送操作
	if(! empty($data['test']))
	{
	    echo '测试的';
		test_send_message($data);		//测试的
	}
	else
	{
        echo '正式推送';
		send_message($data);			//正式推送
	}	
	
    //返回任务执行的结果
    $serv->finish("finish");
});
 
 
//处理异步任务的结果
$serv->on('finish', function ($serv, $task_id, $data) {
    echo "异步任务执行完成";
});
 
 
$serv->start();

function handleFun($post_data){

    print_r($post_data);

    if (! empty($post_data))
    {
        $url 		=	$post_data['call_back'];		//通知url
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch,CURLOPT_TIMEOUT,3);  //定义超时3秒钟
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        //执行并获取url地址的内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
    }
}

function send_message($postdata)
{
	$ch = curl_init(); //用curl发送数据给api
    curl_setopt( $ch, CURLOPT_POST, true );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_URL, $postdata['url']);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($postdata['data'],true));
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
    $response = curl_exec($ch);
    curl_close( $ch );
    $rest = json_decode($response,true);


    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);

    //$redis->rPush('do_data',json_encode($rest).json_encode($postdata));

	//记录发送成功的
	if(! empty($rest))
	{
		if($rest['errcode'] == 0 || $rest['errmsg'] == 'ok')
		{
            //记录失败的用户
            $success_message	=	'success_'.$postdata['game'];
            $redis->rPush($success_message,$postdata['data']['touser']);
		}
		else
		{
			//记录失败的用户
			$fail_message	=	'fail_'.$postdata['game'];
			$redis->rPush($fail_message,$postdata['data']['touser']);
		}
	}
}

//=========================================  测试专用 无情的分界线	=================================		
function test_send_message($postdata)
{
	//记录发送成功的ID
	//$success_message 	=	'successed_message_'.$postdata['game'];
	//$fail_message	=	'successed_message_'.$postdata['game'];
	//$redis = new Redis();
	//$redis->connect('127.0.0.1', 6379);
	//$redis->rPush($success_message,$postdata['id']);
}

function test_handleFun($post_data)
{
    print_r($post_data);

	if (! empty($post_data))
    {
        /*
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);

        $update_message     =   'update_'.$post_data['game'];


        while(true){
            try{
                $value = $redis->lpop($update_message);
                if(!$value){
                    break;
                }

                echo $update_message.'的值'.$value;
            }catch(Exception $e){
                echo $e->getMessage();
            }
        }
        */


        $url 		=	$post_data['call_back'];		//通知url
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch,CURLOPT_TIMEOUT,3);  //定义超时3秒钟
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        //执行并获取url地址的内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);

    }
}



 
 ?>